package com.hnyc.token;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisKeyExpiredEvent;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 监听redis中的键过期事件
 * 只有redis 2.8以后才支持
 * 需要在redis启动的开启配置项：notify-keyspace-events Ex
 * @auther zero
 * @date 2023/3/13
 **/
@Slf4j
@Configuration
public class RedisKeyListener {


        @Bean
        public RedisMessageListenerContainer listenerContainer(RedisConnectionFactory connectionFactory) {
            RedisMessageListenerContainer container = new RedisMessageListenerContainer();
            container.setConnectionFactory(connectionFactory);
            return container;
        }


        @Bean
        public KeyExpirationEventMessageListener keyExpirationEventMessageListener(RedisMessageListenerContainer listenerContainer) {
            return new KeyExpirationEventMessageListener(listenerContainer);
        }

//        @Bean
//        public ApplicationListener applicationListener() {
//            return (ApplicationListener<RedisKeyExpiredEvent>) event -> {
//                log.info("监听到键过期消息，消息对应的键为：{}，消息所属的channel为：{}", new String(event.getSource()), event.getChannel());
//                // notify refresh
//            };
//        }
        @Component
        public static class RedisKeyExpiredListener implements ApplicationListener<RedisKeyExpiredEvent>{
            @Resource
            TokenManager tokenManager;
            @Override
            public void onApplicationEvent(RedisKeyExpiredEvent event) {
                log.info("监听到键过期消息，消息对应的键为：{}，消息所属的channel为：{}", new String(event.getSource()), event.getChannel());
                tokenManager.refreshToken(new String(event.getSource()));
            }
        }

}
